package com.study.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: MaxLenthChildString   字符串中的最长子串
 * @date: 2020/11/20 20:02
 * @author: hcm
 * @version: 1.0
 */
public class MaxLenthChildString {

    public static void main(String[] args) {
        String testData = "dvdf";
        int res = lengthOfLongestSubstring(testData);
        System.out.println("最长字串的长度："+res);
    }

    /**
     * 求出最长字串长度
     *
     * @param s
     * @return
     */
    public static int lengthOfLongestSubstring(String s) {

        //转换成字符数组
        char[] charArray = s.toCharArray();
       // System.out.println("初始长度："+ charArray.length);

        //最长
        int maxLen = 0;

        //计数
        int count = 0;

        //记录已存在
        final String hadData = "exist";

        //hash存取
        Map m = new HashMap();

       // System.out.println("初始长度" + m.size());

        //遍历
        for (int i = 0; i < charArray.length; i++) {

            //初始
            if (m.size() == 0) {
                m.put(charArray[i], hadData);
                count++;
                if(maxLen<count){
                    maxLen = count;
                }
                continue;
            }


            //记数条件 连续>>>HashMap 检测key是否存在
            if (!hadData.equals(m.get(charArray[i]))){
                //数据未存在
                m.put(charArray[i],hadData);
                count++;
            }else {
                if(maxLen<count){
                    maxLen = count;
                }

                count = 0;
                i-=m.size();
                m.clear();
            }
            if(maxLen<count){
                maxLen = count;
            }
        }
        return maxLen;
    }

}
